<?php

namespace App\Admin\Controllers;

use App\Models\Family;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class FamilyController extends Controller
{
    use ModelForm;

    public $header = '家庭列表';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form1()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Family::class, function (Grid $grid) {

            $grid->id('编号')->sortable();
            $grid->number('户号');
            $grid->address('地址');
            $grid->householder()->username('户主');
            $grid->userDetails('家庭成员')->display(function ($val){
                $return = count($val) . '个成员<br>';
                foreach ($val as $k=>$v){
                    if ($v['is_householder']){
                        $return .= '<span class="label label-success">'.$v['username'].'</span> ';
                    } else {
                        $return .= '<span class="label label-primary">'.$v['username'].'</span> ';
                    }
                }

                return $return;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();
                //$actions->prepend('<a href="/admin/familyUsers/create?fid='.$actions->getKey().'"><i class="fa fa-plus"></i>添加成员</a>');
            });

            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->like('number', '户号');
                $filter->like('address', '地址');
                $filter->like('householder.username', '户主');
                $filter->between('created_at', '添加时间')->datetime();
            });

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Family::class, function (Form $form) {

            $form->display('id', '编号');
            $form->text('number', '户号')->rules('required');
            $form->text('address', '地址')->rules('required');

            $form->select('householder_id','户主')->options(
                User::whereNotIn('id', function ($query){
                    $query->select('user_id')->from('love_family_users')->get();
                })->pluck('username', 'id')
            )->setWidth(4);

            $form->multipleSelect('user', '成员')->options(
                User::whereNotIn('id', function ($query){
                    $query->select('user_id')->from('love_family_users')->get();
                })->pluck('username', 'id')
            );

            $form->display('created_at', '创建时间');

            $form->disableViewCheck();

            $form->saving(function (Form $form){

                $householder_id = $form->householder_id;//户主id
                $user = array_filter($form->user);//成员数组
                $family_id = $form->model()->id;//家庭id

                //用户是否在其他家庭里
                $user_count = Family\User::where('user_id', $householder_id)
                    ->when($family_id,function ($query) use ($family_id) {
                        return $query->where('family_id', '<>', $family_id);
                    })->count();

                if ($user_count){
                    $error = new MessageBag([
                        'title'   => '添加失败',
                        'message' => '户主已经在其他家庭里存在',
                    ]);

                    return back()->with(compact('error'));
                }

                //判断成员是否在其他家庭中
                if (!in_array($householder_id, $user))
                    $user[] = $householder_id;

                $user_row = Family\User::whereIn('user_id', $user)
                    ->when($family_id,function ($query) use ($family_id) {
                        return $query->where('family_id', '<>', $family_id);
                    })->with('user')->get()->toArray();

                if ($user_row){
                    $u = [];
                    foreach ($user_row as $key => $val) {
                        $u[] = $val['user']['username'];
                    }

                    $u = implode(',', $u);

                    $error = new MessageBag([
                        'title'   => '添加失败',
                        'message' => "成员 $u 已经在其他家庭里存在",
                    ]);

                    return back()->with(compact('error'));
                }

                $user[] = null;
                $form->user = $user;

            });

            $form->saved(function (Form $form){

                //保存之后设置户主

                $family_id = $form->model()->id;
                $householder_id = $form->model()->householder_id;

                Family\User::where('is_householder', 1)
                    ->where('family_id', $family_id)
                    ->update(['is_householder' => 0]);

                $user = Family\User::where('family_id', $family_id)
                    ->where('user_id', $householder_id)->first();

                if ($user) {
                    $user->is_householder = 1;
                    $user->update();
                } else {
                    $user = new Family\User;
                    $user->family_id = $family_id;
                    $user->user_id = $householder_id;
                    $user->is_householder = 1;

                    $user->save();
                }

            });
        });
    }

    protected function form1()
    {
        return Admin::form(Family::class, function (Form $form) {

            $form->display('id', '编号');
            $form->text('number', '户号')->rules('required');
            $form->text('address', '地址')->rules('required');

            $form->select('householder_id','户主')->options(
                User::all()->pluck('username', 'id')
            )->setWidth(4)->rules('required');

            $form->multipleSelect('user', '成员')->options(
                User::all()->pluck('username', 'id')
            );

            $form->display('created_at', '创建时间');

            $form->disableViewCheck();

        });
    }

    public function destroy($id)
    {
        $user_count = Family\User::where('family_id', $id)->count();
        if ($user_count) {
            admin_toastr('删除失败,该家庭下有成员存在,不能直接删除', 'error');
        } else {
            $status = Family::where('id', $id)->delete();

            if ($status){
                admin_toastr('删除成功', 'success');
            } else {
                admin_toastr('删除失败', 'error');
            }
        }

    }



}
